package com.andyyan.ai.chatbot.controllers;

import com.andyyan.ai.chatbot.model.ApiResult;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.UUID;

import static com.andyyan.ai.chatbot.constant.ChatBotConstant.USER_ID;

@Slf4j
@RestController
@RequestMapping("/api/ai/user")
public class UserController {

    // 模拟用户登录
    @RequestMapping("/login")
    public ApiResult<?> login(HttpServletResponse response,
                              @CookieValue(value = USER_ID, required = false) String userId) {
        if (StringUtils.isNotBlank(userId)) {
            // 已登录，无需登录
            return ApiResult.fail(1, "已登录", null);
        }

        // 使用UUID 当做用户
        userId = UUID.randomUUID().toString().replaceAll("-", "");
        ResponseCookie cookie = ResponseCookie.from(USER_ID, userId)
                .httpOnly(true)
                .secure(true)
                .path("/")
                .maxAge(Duration.ofDays(7))
                .sameSite("Lax") // 防止CSRF攻击
                .build();
        response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString());
        log.info("userId:{}, login success", userId);
        return ApiResult.success(null);
    }

    // 模拟退出登录
    @RequestMapping("/logout")
    public ApiResult<?> logout(HttpServletResponse response,
                               @CookieValue(value = USER_ID, required = false) String userId) {
        if (StringUtils.isBlank(userId)) {
            return ApiResult.fail(3, "未登录", null);
        }
        ResponseCookie cookie = ResponseCookie.from(USER_ID, "")
                .maxAge(0)
                .path("/")
                .build();
        response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString());
        log.info("userId:{}, logout success", userId);
        return ApiResult.success(null);
    }

}
